package com.hou.lang;

import java.lang.ref.WeakReference;

public class WeakTest {

    public static void main(String[] args) {
        //通过WeakReference的get()方法获取弱引用对象
        WeakReference<User> userWeakReference = new WeakReference<>(new User("hou"));
        System.out.println("User:" + userWeakReference.get());
        System.gc();
        try {
            //休眠一下，在运行的时候加上虚拟机参数-XX:+PrintGCDetails，输出gc信息，确定gc发生了。
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //如果为空，代表被回收了,如果是强引用, User user=new User("name"); 则不会回收
        if (userWeakReference.get() == null) {
            System.out.println("user已经被回收");
        }
    }
}
